package com.example.zhidao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zhidao.dao.UserMapper;
import com.example.zhidao.model.Spage.ShowPage;
import com.example.zhidao.model.po.*;
import com.example.zhidao.model.responseData.ResponseData;
import com.example.zhidao.model.vo.UserVo;
import com.example.zhidao.service.AdminService;
import com.example.zhidao.service.EmailService;
import com.example.zhidao.service.FansService;
import com.example.zhidao.service.UserService;
import com.example.zhidao.utils.Ujwt;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {//9

//    考虑到微信登录的用户，将使用password存储code，用户名在生成的那一瞬，直接随机生成一个给他，且用户的type上为普通用户，2为微信用户，0为封禁用户



    @Autowired
    private UserService userService;

    @Autowired
    private Ujwt ujwt;

    @Autowired
    private FansService fansService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private AdminService adminService;

    @Resource
    private UserMapper userMapper;

//    查询用户接口 分页
//    该接口给后台给用户使用
    @GetMapping("/list")
    public ResponseData allUserPage(Page p){
        Page userList=userService.page(p);

//        处理数据，进行数据脱敏
        List<User> userList1=userList.getRecords();
        List<UserVo> result=new ArrayList<>();
        for(User u:userList1){
            UserVo uv=new UserVo();
            uv.setId(u.getId());
            uv.setUsername(u.getUsername());
            uv.setImg(u.getImg());
            uv.setConcern(u.getConcern());
            uv.setFan(u.getFan());
            uv.setEmail(u.getEmail());
            uv.setPublish(u.getPublish());
            uv.setCreatetime(u.getCreatetime());
            uv.setCollection(u.getCollection());
            uv.setSex(u.getSex());
            uv.setType(u.getType());

            result.add(uv);
        }
        userList.setRecords(result);
        if(userList==null){
            return new ResponseData(userList,false,"查询失败",201);
        }else{
            return new ResponseData(userList,true,"查询成功",200);
        }
    }

//    修改用户接口
    @PatchMapping
    public ResponseData updateUser(@RequestBody User user){
        UpdateWrapper uw=new UpdateWrapper();
        uw.eq("id",user.getId());
        uw.set(user.getSex()!=null,"sex",user.getSex());
        uw.set(user.getImg()!=null,"img",user.getImg());
        uw.set(user.getEmail()!=null,"email",user.getEmail());
        uw.set(user.getPassword()!=null,"password",user.getPassword());
        Boolean b=userService.update(uw);
        if(b){
            return new ResponseData(b,true,"修改成功",200);
        }else{
            return new ResponseData(b,false,"修改失败",201);
        }
    }

//    注销用户
    @DeleteMapping
    public ResponseData deleteUser(User user){
        user.setCollection(0);
        Boolean b=userService.removeById(user.getId());
        System.out.println(b);;
        if(b){
            return new ResponseData(b,true,"注销成功",200);
        }else{
            return new ResponseData(b,false,"注销失败",201);
        }
    }

//    创建用户接口
    @PostMapping("/register")
    public ResponseData createUser(@RequestBody User user,String code){

//        现根据code  和邮箱查找最新的一条email的code进行对比，并且email的code失效为2分钟
        QueryWrapper<Email> qw1=new QueryWrapper<>();
        qw1.eq("uemail",user.getEmail());
        qw1.eq("code",code);

        Email e=emailService.getOne(qw1);

        if(e==null){
            return new ResponseData(null,false,"没有邮箱验证code",203);
        }else{
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(e.getCreatetime());

                  // 在 Calendar 对象上加上两分钟
            calendar.add(Calendar.MINUTE, 2);

                // 获取加上两分钟后的时间
            Date codetime = calendar.getTime();
            Date date=new Date();
            if(codetime.before(date)){
                return new ResponseData(null,false,"邮箱验证已过期，请重新验证",204);
            }else{
                //        先判断又没这个账号
                QueryWrapper<User> qw=new QueryWrapper<>();
                qw.eq("username",user.getUsername());
                User user1=userService.getOne(qw);
                System.out.println(user1);
                if(user1==null) {


//            进行数据的安全性处理,防止用户创建时给我乱改
                    user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
                    user.setCollection(0);
                    user.setConcern(0);
                    user.setFan(0);
                    user.setToken(null);
                    user.setType(1);
                    Date d=new Date();
                    user.setCreatetime(d);

                    Boolean b = userService.save(user);

                    System.out.println(b);
                    if (b) {
                        return new ResponseData(b, true, "创建成功", 200);
                    } else {
                        return new ResponseData(b, false, "创建失败", 201);
                    }
                }else{
                    return new ResponseData("",false, "用户名已存在", 202);
                }
            }
        }


    }

//    用户登录接口
    @GetMapping("/login")
    public ResponseData login(String username,String password){
        if(username==null || password==null){
            return new ResponseData(null,false,"输入的账号或密码为空",203);
        }else{
            QueryWrapper<User> qw=new QueryWrapper<>();
            qw.eq("username",username);
            qw.eq("password",password);
            User u=userService.getOne(qw);
         if(u==null){
             return new ResponseData(u,false,"该用户名密码不存在",202);
         }else{
             if(u.getType()==0){
                 return new ResponseData(null,false,"该用户已被封号",205);
             }else{
                 String token=ujwt.getoken(u);//对从user中的id name两个字段进行加密，并设置时间进行7天免密登录
                 System.out.println(token);
                 UpdateWrapper<User> uw=new UpdateWrapper<>();
                 uw.eq("id",u.getId());
                 uw.set("token",token);
                 boolean i=userService.update(uw);

                 if(i){
                     return new ResponseData(token,true,"登录成功，返回token",200);
                 }else{
                     return new ResponseData(null,false,"登录失败",201);
                 }
             }
         }
        }
    }

//    用户登陆有后根据token信息返回用户的信息
    @GetMapping("/info")
    public ResponseData getuserinfo(@RequestHeader("token") String token){

           Claims claims=(Claims)ujwt.tokenToOut(token);//强制转换属性
           QueryWrapper<User> qw=new QueryWrapper<>();
           qw.eq("id",claims.getId());
           User u=userService.getOne(qw);

//           数据脱密
           UserVo uv=new UserVo();
           uv.setId(u.getId());
           uv.setUsername(u.getUsername());
           uv.setImg(u.getImg());
           uv.setConcern(u.getConcern());
           uv.setFan(u.getFan());
           uv.setEmail(u.getEmail());
           uv.setPublish(u.getPublish());
           uv.setCreatetime(u.getCreatetime());
           uv.setCollection(u.getCollection());
           uv.setSex(u.getSex());
           uv.setType(u.getType());


           return new ResponseData(uv,true,"成功获取用户信息",200);

    }

//    根据用户id获取用户的信息
    @GetMapping("/otherInfo")
    public ResponseData getOtherInfo(String uid,String mid){

        QueryWrapper<User> qw=new QueryWrapper<>();
        qw.eq("id",uid);
        User u=userService.getOne(qw);

//           数据脱密
        UserVo uv=new UserVo();
        uv.setId(u.getId());
        uv.setUsername(u.getUsername());
        uv.setImg(u.getImg());
        uv.setConcern(u.getConcern());
        uv.setFan(u.getFan());
        uv.setEmail(u.getEmail());
        uv.setPublish(u.getPublish());
        uv.setCreatetime(u.getCreatetime());
        uv.setCollection(u.getCollection());
        uv.setSex(u.getSex());
        uv.setType(u.getType());


//        再根据这个id去数据库里面寻找有没有关注这个人

        if(uv!=null) {

            if (mid == null) {
                return new ResponseData(uv, true, "无", 200);
            }else{
                QueryWrapper<Fans> qw1 = new QueryWrapper<>();
                qw1.eq("fansid",mid);
                qw1.eq("uid",uid);
                Fans fans = fansService.getOne(qw1);

                if (fans != null) {
                    return new ResponseData(uv, true, "有", 200);
                } else {
                    return new ResponseData(uv, true, "无", 200);
                }
            }
        }else{
            return new ResponseData(uv,true,"获取失败",201);
        }


    }


    //    用户修改接口
    @PutMapping("/update")//记得加一下
    public ResponseData updateUser(@RequestHeader("token") String token,@RequestBody User user,String code){

        Claims claims=(Claims)ujwt.tokenToOut(token);//强制转换属性



//        现根据code  和邮箱查找最新的一条email的code进行对比，并且email的code失效为2分钟
        QueryWrapper<Email> qw1=new QueryWrapper<>();
        qw1.eq("uemail",user.getEmail());
        qw1.eq("code",code);

        Email e=emailService.getOne(qw1);

        if(e==null){
            return new ResponseData(null,false,"没有邮箱验证code",203);
        }else{
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(e.getCreatetime());

            // 在 Calendar 对象上加上两分钟
            calendar.add(Calendar.MINUTE, 2);

            // 获取加上两分钟后的时间
            Date codetime = calendar.getTime();
            Date date=new Date();
            if(codetime.before(date)){
                return new ResponseData(null,false,"邮箱验证已过期，请重新验证",204);
            }else{
                //        先判断又没这个账号
                QueryWrapper<User> qw=new QueryWrapper<>();
                qw.eq("username",user.getUsername());
                User user1=userService.getOne(qw);
                System.out.println(user1);
                if(user1!=null) {
                    if(!user1.getId().equals(claims.getId())){
                        return new ResponseData(null,false, "你不是这个号的用户", 206);
                    }
                    if(!user1.getEmail().equals(user.getEmail())){
                        return new ResponseData(null,false, "邮箱不对", 206);
                    }

                  UpdateWrapper<User> uw=new UpdateWrapper<>();
                  uw.eq("id",user1.getId()).set("username",user.getUsername()).
                          set("sex",user.getSex()).set(user.getImg()!="","img",user.getImg());


                    Boolean b = userService.update(uw);

                    System.out.println(b);
                    if (b) {
                        return new ResponseData(b, true, "修改成功", 200);
                    } else {
                        return new ResponseData(b, false, "修改失败", 201);
                    }
                }else{
                    return new ResponseData("",false, "用户名不存在", 202);
                }
            }
        }


    }

//    用户忘记密码并进行修改
    @PutMapping("/lostpass")
    public ResponseData lostPass(String code,@RequestBody User user){
        //        现根据code  和邮箱查找最新的一条email的code进行对比，并且email的code失效为2分钟
        QueryWrapper<Email> qw1=new QueryWrapper<>();
        qw1.eq("uemail",user.getEmail());
        qw1.eq("code",code);

        Email e=emailService.getOne(qw1);

        if(e==null){
            return new ResponseData(null,false,"没有邮箱验证code",203);
        }else{
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(e.getCreatetime());

            // 在 Calendar 对象上加上两分钟
            calendar.add(Calendar.MINUTE, 2);

            // 获取加上两分钟后的时间
            Date codetime = calendar.getTime();
            Date date=new Date();
            if(codetime.before(date)){
//               清除不必要的数据
                emailService.removeById(e);
                return new ResponseData(null,false,"邮箱验证已过期，请重新验证",204);
            }else{
                //        先判断又没这个账号
                QueryWrapper<User> qw=new QueryWrapper<>();
                qw.eq("username",user.getUsername());
                qw.eq("email",user.getEmail());
                User user1=userService.getOne(qw);
                //               清除不必要的数据
                emailService.removeById(e);
                if(user1==null) {
                    return new ResponseData(null,false,"该账号不存在，或者邮箱错误",202);
                }else{
                    UpdateWrapper<User> uw=new UpdateWrapper<>();
                    uw.eq("id",user1.getId()).set("password",user.getPassword());

                    boolean i=userService.update(uw);
                    if(i){
                        return new ResponseData(i, true, "修改成功", 200);
                    } else {
                        return new ResponseData(i, false, "修改失败", 201);
                    }
                }
                }
                }
                }




//  以下为管理员专用的接口

//    多条件获取数据
    @GetMapping("/admin/get")
    public ResponseData adminget(@RequestHeader String token,
                                 String username,String sex,Integer type,
                                 String condition,String sort,
                                 @RequestParam(defaultValue = "1") Integer page ,
                                 @RequestParam(defaultValue = "10") Integer pageSize){


        Claims claims=(Claims)ujwt.tokenToOut(token);//强制转换属性
        String aid=claims.getId();
        QueryWrapper<Admin> q=new QueryWrapper();
        q.eq("id",aid);
        if(adminService.getOne(q)==null){
            return new ResponseData(null,false,"你不是管理员",300);
        }

        ShowPage showPage = new ShowPage();
        Integer pageBegin = (page-1) * pageSize;

        //当前页码
        showPage.setPageNum(page);
        //前（后）一页页码
        showPage.setPrePage(page - 1);
        showPage.setNextPage(page + 1 );
        //总数据条数
        showPage.setSize(userMapper.getuserListTotal(username,type,sex,condition,sort).size());
        //开始（末尾）数据是第几行
        showPage.setStartRow(pageBegin + 1);
        showPage.setEndRow(pageBegin + pageSize + 1);
        //每页数据条数
        showPage.setPageSize(pageSize);
        //总页数
        Integer div = showPage.getSize()/pageSize;
        Integer pages = showPage.getSize() % pageSize == 0 ? div : div + 1;
        showPage.setPages(pages);
        //是否是第（最后）一页,是否有前（后）一页
        showPage.setIsFirstPage(page == 1);
        showPage.setHasPreviousPage(page != 1);
        showPage.setIsLastPage(page.equals(pages));
        showPage.setHasNextPage(!page.equals(pages));

        showPage.setData(userMapper.getuserList(username,type,sex,condition,sort,pageBegin,pageSize));


        return new ResponseData(showPage,true,"成功获取",200);
    }



//    删除用户
    @DeleteMapping("/admin/del")
    public ResponseData delUser(@RequestHeader String token,String id){

        Claims claims=(Claims)ujwt.tokenToOut(token);//强制转换属性
        String aid=claims.getId();
        QueryWrapper<Admin> q=new QueryWrapper();
        q.eq("id",aid);
        if(adminService.getOne(q)==null){
            return new ResponseData(null,false,"你不是管理员",300);
        }


        boolean i=userService.removeById(id);

        if(i){
            return new ResponseData(i,true,"成功删除",200);
        }else{
            return new ResponseData(null,false,"删除失败",201);
        }

    }

//    修改用户
    @PutMapping("/admin/update")
    public ResponseData update(@RequestHeader String token,String id ,int type){

        Claims claims=(Claims)ujwt.tokenToOut(token);//强制转换属性
        String aid=claims.getId();
        QueryWrapper<Admin> q=new QueryWrapper();
        q.eq("id",aid);
        if(adminService.getOne(q)==null){
            return new ResponseData(null,false,"你不是管理员",300);
        }

        System.out.println("1111111111111111111111111111111111111");
       UpdateWrapper<User> uw=new UpdateWrapper<>();
       uw.eq("id",id).set("type",type);

       boolean i=userService.update(uw);

        if(i){
            return new ResponseData(i,true,"修改删除",200);
        }else{
            return new ResponseData(null,false,"修改失败",201);
        }
    }



}
